package net.hvacapp.cmvrfforandroid.ui.selections;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.mirror.android.common.util.StringUtils;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.ui.BaseActivity;
import net.hvacapp.cmvrfforandroid.ui.selections.model.AreaData;
import net.hvacapp.cmvrfforandroid.ui.selections.model.GetAreaDataResp;
import net.hvacapp.cmvrfforandroid.widget.IOSAlertView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@EActivity(R.layout.activity_selection_province)
public class SelectionProvinceActivity extends BaseActivity {

    @ViewById(R.id.lv_province)
    ListView mProvinceLv;

    private boolean mIsMultipleSelection;
    private ArrayList<AreaData> mSelectedData;
    private ArrayList<AreaData> mSelectedNation;

    private QuickAdapter<AreaData> mQuickAdapter;

    /**
     * 页面加载完后执行
     */
    @AfterViews
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        initEvent();
    }

    /**
     * 初始化
     */
    @Override
    public void initBoot() {
        setupToolbar(0, "选择省份", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectedData == null || mSelectedData.size() == 0) {

                    IOSAlertView.showAlertView(SelectionProvinceActivity.this, "提示",
                            "还没有选择省份，确定返回？", "确定",
                            new IOSAlertView.OnAlertViewClickListener() {

                                @Override
                                public void OnAlertViewClick(int position) {
                                    if (position == 0) {
                                        Intent intent = new Intent();
                                        Bundle bundle = new Bundle();
                                        bundle.putParcelableArrayList("province", mSelectedData);
                                        intent.putExtras(bundle);
                                        setResult(RESULT_OK, intent);
                                        finish();
                                    }
                                }
                            }, "取消");

                }
                else {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList("province", mSelectedData);
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
        if (mQuickAdapter == null){
            mQuickAdapter = new QuickAdapter<AreaData>(context, R.layout.one_line_cell_item) {
                @Override
                protected void convert(BaseAdapterHelper helper, AreaData item) {
                    if (StringUtils.isEquals(item.getGuidId(), item.getNationId())) {
                        helper.setTextColor(R.id.tv_title, getResources().getColor(R.color.cm_blue_color));
                    }
                    else {
                        helper.setTextColor(R.id.tv_title, getResources().getColor(R.color.cm_table_title_text_color));
                    }

                    if (item.isSelected() == 1) {
                        helper.setVisible(R.id.iv_selected_mark, true);
                    }
                    else {
                        helper.setVisible(R.id.iv_selected_mark, false);
                    }
                    helper.setText(R.id.tv_title, item.getName());
                }
            };
        }

        mProvinceLv.setAdapter(mQuickAdapter);
    }

    /**
     * 初始化数据
     */
    @Override
    public void initData(Intent intent) {
        mIsMultipleSelection = intent.getBooleanExtra("multiple", true);
        mSelectedNation = intent.getParcelableArrayListExtra("nation");
        mSelectedData = intent.getParcelableArrayListExtra("province");
        if (mSelectedNation != null) {
            for (int i = 0; i < mSelectedNation.size(); i ++) {
                loadProvinceData(mSelectedNation.get(i));
            }
        }
    }

    /**
     * 页面名称
     */
    @Override
    public String getName() {
        return "";
    }

    private void initEvent() {
        mProvinceLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AreaData data = (AreaData) parent.getItemAtPosition(position);

                if (StringUtils.isEquals(data.getGuidId(), data.getNationId())) {
                    return;
                }


                if (mIsMultipleSelection) {
                    ImageView ivSelectMark = (ImageView)view.findViewById(R.id.iv_selected_mark);
                    if (data.isSelected() == 1) {
                        data.setIsSelected(0);
                        ivSelectMark.setVisibility(View.INVISIBLE);
                    }
                    else {
                        data.setIsSelected(1);
                        ivSelectMark.setVisibility(View.VISIBLE);
                    }
                    resetSelectedData(data);
                }
                else {

                    if (mSelectedData == null) {
                        mSelectedData = new ArrayList<AreaData>();
                    }
                    else {
                        mSelectedData.clear();
                    }
                    mSelectedData.add(data);
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList("province", mSelectedData);
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
    }

    private void loadProvinceData(final AreaData nation) {
        Map<String, Object> param = new HashMap<>();
        param.put("nid", nation.getGuidId());
        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROVINCES, param, new HttpCallbackHandle<GetAreaDataResp>() {
            @Override
            public void onSuccess(GetAreaDataResp obj) {
                // 成功
//                mQuickAdapter.clear();
                nation.setNationId(nation.getGuidId());
                nation.setIsSelected(0);
                mQuickAdapter.add(nation);

                if (mSelectedData != null && mSelectedData.size() > 0) {
                    if (obj.getGetAllProvincesResult().size() > 0) {
                        for (int i = 0; i < obj.getGetAllProvincesResult().size(); i++) {
                            AreaData item = obj.getGetAllProvincesResult().get(i);
                            for (int j = 0; j < mSelectedData.size(); j++) {
                                if (StringUtils.isEquals(item.getGuidId(), mSelectedData.get(j).getGuidId())) {
                                    item.setIsSelected(1);
                                    break;
                                }
                            }
                            mQuickAdapter.add(item);
                        }
                    }
                } else {
                    if (obj.getGetAllProvincesResult().size() > 0) {
                        mQuickAdapter.addAll(obj.getGetAllProvincesResult());
                    }
                }
            }

            @Override
            public void onFailure(String response) {
                showMessage("数据加载失败");
            }

        });
    }

    private void resetSelectedData(AreaData data) {
        if (data.isSelected() == 1) {
            if (mSelectedData == null) {
                mSelectedData = new ArrayList<>();
            }
            boolean hasSame = false;
            for (AreaData item : mSelectedData) {
                if (StringUtils.isEquals(data.getGuidId(), item.getGuidId())) {
                    hasSame = true;
                    break;
                }
            }
            if (!hasSame) {
                mSelectedData.add(data);
            }
        }
        else {
            if (mSelectedData != null && mSelectedData.size() > 0) {
                for (AreaData item : mSelectedData) {
                    if (StringUtils.isEquals(data.getGuidId(), item.getGuidId())) {
                        mSelectedData.remove(item);
                        break;
                    }
                }
            }
        }
    }


}
